<template>
  <div class="lr-top">
    <div v-if="appConfig.theme.nav == 'mix'" class="top-bar__left">
      <top-logo ref="topLogo"></top-logo>
      <div class="top-bar__item">
        <top-menu ref="topMenu"></top-menu>
      </div>
    </div>
    <div class="top-bar__right">
      <el-tooltip effect="dark" :content="isFullScren ? $t('退出全屏') : $t('全屏')" placement="bottom">
        <div class="top-bar__item">
          <i :class="isFullScren ? 'el-icon-full-screen' : 'el-icon-full-screen'" @click="handleScreen"></i>
        </div>
      </el-tooltip>
      <el-tooltip v-if="isOpenIMChat" effect="dark" :content="$t('联系')" placement="bottom">
        <div class="top-bar__item" @click="handleOpenChat">
          <i class="el-icon-chat-dot-square"></i>
          <el-badge v-if="chatNum" :value="chatNum" :max="99" style="margin-left: -8px; margin-top: -8px"></el-badge>
        </div>
      </el-tooltip>

      <el-tooltip v-if="isOpenIMMessage" effect="dark" :content="$t('消息')" placement="bottom">
        <div class="top-bar__item" style="margin-right: 16px" @click="handleOpenMessge">
          <i class="el-icon-bell"></i>
          <el-badge
            v-if="messageNum"
            :value="messageNum"
            :max="99"
            style="margin-left: -8px; margin-top: -8px"
          ></el-badge>
        </div>
      </el-tooltip>

      <el-dropdown>
        <div class="el-dropdown-link">
          <el-avatar :size="24" :src="avatar">
            <img :src="`${rootUrl}img/admin/head.png`" />
          </el-avatar>
          {{ loginInfo.f_RealName }}
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <router-link to="/organization/loginuser/index">{{ $t("个人信息") }}</router-link>
          </el-dropdown-item>
          <el-dropdown-item @click.native="handleRemoveCache">
            {{ $t("清空缓存") }}
          </el-dropdown-item>
          <el-dropdown-item @click.native="handleFramework">
            {{ $t("关于框架") }}
          </el-dropdown-item>
          <el-dropdown-item @click.native="logout" divided>{{ $t("退出登录") }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <div class="top-bar__item">
        <top-lang></top-lang>
      </div>
      <div class="top-bar__item" style="margin: 0">
        <i class="el-icon-s-operation" @click.stop="openFrameworkSetting"></i>
      </div>
    </div>

    <l-dialog :title="$t('关于框架')" :visible.sync="frameworkVisible" :hasBtns="false" :height="240" width="560px">
      <div class="l-rblock">
        <img class="l-framework-img" :src="`${rootUrl}img/admin/logo2.svg`" />
        <div class="l-framework-text">
          <div class="l-framework-title">
            <a :href="appConfig.url" target="_blank"> {{ appConfig.title }}</a>
          </div>
          <div>{{ $t("版本") }}：{{ appConfig.version }}-{{ appConfig.subVersion }}</div>
        </div>
        <div class="l-framework-footer">
          <a :href="appConfig.url" target="_blank">{{ appConfig.company }}</a>
        </div>
      </div>
    </l-dialog>

    <l-drawer
      :title="$t('框架设置')"
      :visible.sync="frameworkSettingVisible"
      :showOk="false"
      :showClose="false"
      size="320px"
    >
      <div class="l-rblock" style="padding: 16px">
        <h3 class="l-framework-setting-title">导航模式</h3>
        <div class="l-framework-setting-checkbox">
          <el-tooltip class="item" effect="dark" content="侧边菜单布局" placement="top">
            <div class="l-framework-setting-checkbox-item l-framework-setting-side" @click="handleNavClick('side')">
              <i class="el-icon-check l-framework-setting-icon" v-if="appConfig.theme.nav == 'side'"></i>
            </div>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="混合菜单布局" placement="top">
            <div class="l-framework-setting-checkbox-item l-framework-setting-mix" @click="handleNavClick('mix')">
              <i class="el-icon-check l-framework-setting-icon" v-if="appConfig.theme.nav == 'mix'"></i>
            </div>
          </el-tooltip>
        </div>
      </div>
    </l-drawer>

    <!--聊天消息-->
    <l-drawer
      :title="$t('联系')"
      :visible.sync="chatVisible"
      :showOk="false"
      :showClose="false"
      size="360px"
      @opened="handleChatOpened"
    >
      <chat-list ref="chatList"></chat-list>
    </l-drawer>

    <!--消息-->
    <l-drawer
      :title="$t('站内消息')"
      :visible.sync="messageVisible"
      :showOk="false"
      :showClose="false"
      size="360px"
      @opened="handleMessageOpened"
      @closed="handleMessageClosed"
    >
      <message-list ref="messageList"></message-list>
    </l-drawer>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { fullscreenToggel, listenfullscreen } from "@/core/util/util";
import topMenu from "./top-menu";
import topLang from "./top-lang";
import topLogo from "./top-logo";

import ChatList from "./chatList.vue";
import MessageList from "./messageList.vue";
export default {
  components: {
    topMenu,
    topLang,
    topLogo,
    ChatList,
    MessageList,
  },
  name: "top",
  provide() {
    return {
      top: this,
    };
  },
  data() {
    return {
      frameworkVisible: false,
      frameworkSettingVisible: false,

      isOpenIM: true,
      isOpenIMChat: false,
      isOpenIMMessage: true,

      connection: null,

      chatNum: 0,
      chatVisible: false,

      messageNum: 0,
      messageVisible: false,
    };
  },
  filters: {},
  created() {},
  mounted() {
    listenfullscreen(this.setScreen);
    this.initIM();
  },
  computed: {
    ...mapGetters(["isFullScren", "modulesGroup"]),
    avatar: function () {
      return this.loginInfo.f_HeadIcon
        ? `${this.apiUrl}organization/user/img/${this.loginInfo.f_HeadIcon}?token=${this.token}`
        : `${this.rootUrl}img/admin/head.png`;
    },
  },
  methods: {
    handleScreen() {
      fullscreenToggel();
    },
    setScreen() {
      this.$store.commit("app/SET_FULLSCREN");
    },
    logout() {
      this.$confirm(this.$t("您确定要退出当前系统吗?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(() => {
          this.$store.dispatch("organization/user/fedLogOut").then(() => {
            this.$router.push({ path: "/login" });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
    handleRemoveCache() {
      this.$confirm(this.$t("您确定要清空缓存吗?"), this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      })
        .then(async () => {
          const api = window.$api.organization.user;
          await api.removeCache();
          location.reload();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
    handleFramework() {
      this.frameworkVisible = true;
    },
    initTopMenu() {
      if (this.appConfig.theme.nav == "side") {
        this.$store.commit("system/module/setMenu", this.modulesGroup["0"] || []);
      } else {
        this.$refs.topMenu && this.$refs.topMenu.initTopMenu();
      }
    },
    openFrameworkSetting() {
      this.frameworkSettingVisible = true;
    },
    handleNavClick(type) {
      this.$store.commit("app/SET_THEME_NAV", type);
      this.$nextTick(() => {
        this.initTopMenu();
      });
    },

    // 即时通讯服务
    async initIM() {
      if (!this.appConfig.imOpen) {
        return;
      }
      const api = window.$api.message.contact;
      const data = (await this.$awaitWraper(api.getList())) || [];
      let num = 0;
      data.forEach((item) => {
        num += item.f_NoReadNum;
      });
      this.chatNum = num;

      // 刷新数据
      const apiMsg = window.$api.message.msg;
      this.messageNum = await this.$awaitWraper(apiMsg.getSysNum());

      this.connection = new window.signalR.HubConnectionBuilder().withUrl(`${this.imUrl}/ChatsHub`).build();

      this.connection.on("revMsg", (userId, msg, dateTime, id, isSystem) => {
        console.log("this.connection revMsg", this.connection);
        if (isSystem == 1) {
          // 系统消息
          //this.messageNum += 1

          if (this.messageVisible && this.$refs.messageList) {
            this.$refs.messageList.refresh();
          } else {
            this.refreshNum();
          }
        } else if (isSystem == 100) {
          // 刷新
          this.refreshNum();
        } else {
          const item = {
            f_MsgId: id,
            f_SendUserId: userId,
            f_RecvUserId: this.loginInfo.f_UserId,
            f_Content: msg,
            f_CreateDate: dateTime,
            f_IsSystem: isSystem,
          };
          if (this.chatVisible && this.$refs.chatList) {
            if (this.$refs.chatList.isAddNum(item)) {
              this.chatNum += 1;
            }
          } else {
            this.chatNum += 1;
          }
          this.$store.commit("message/msg/add", item);
        }
      });

      this.connection.onclose(function () {
        //console.log("Connection closed!", e);
      });

      this.connection
        .start()
        .then(() => {
          console.log("this.connection start", this.connection);
          this.isOpenIM = true;
          this.connection.invoke("SendInfo", this.loginInfo.f_UserId);
        })
        .catch(function (err) {
          console.error(err.toString());
        });
    },

    // 内部聊天
    handleOpenChat() {
      this.chatVisible = true;
    },
    handleChatOpened() {
      this.$refs.chatList && this.$refs.chatList.loadData();
    },
    sendChat(userId, msg, id) {
      if (this.connection.state == 1) {
        this.connection.invoke("SendMsg", this.loginInfo.f_UserId, userId, msg, id, 0);
      }
    },
    updateChatNum(num) {
      this.chatNum -= num;
      if (this.chatNum < 0) {
        this.chatNum = 0;
      }
    },

    // 系统消息
    handleOpenMessge() {
      this.messageVisible = true;
    },
    handleMessageOpened() {
      this.$refs.messageList.refresh();
    },
    updateMessageNum(num) {
      this.messageNum = num;
    },
    handleMessageClosed() {
      this.refreshNum();
    },

    async refreshNum() {
      const api = window.$api.message.msg;
      this.messageNum = await this.$awaitWraper(api.getSysNum());
    },
  },
};
</script>

<style lang="scss" scoped>
.l-framework-img {
  position: absolute;
  top: 64px;
  right: 50%;
  margin-right: 40px;
  height: 64px;
}
.l-framework-text {
  position: absolute;
  top: 73px;
  left: 50%;
  margin-left: -24px;
  width: 284px;
}
.l-framework-title {
  font-size: 18px;
}
.l-framework-footer {
  position: absolute;
  bottom: 16px;
  width: 100%;
  text-align: center;
}
.l-framework-setting {
  &-title {
    margin-top: 0;
    margin-bottom: 12px;
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    line-height: 22px;
    font-weight: 500;
  }
  &-checkbox {
    display: flex;
    min-height: 42px;
  }
  &-checkbox-item {
    position: relative;
    width: 44px;
    height: 36px;
    margin-right: 16px;
    overflow: hidden;
    background-color: #f0f2f5;
    border-radius: 4px;
    box-shadow: 0 1px 2.5px 0 rgb(0 0 0 / 18%);
    cursor: pointer;
  }
  &-checkbox-item:before {
    position: absolute;
    top: 0;
    left: 0;
    width: 33%;
    height: 100%;
    background-color: #fff;
    content: "";
  }
  &-checkbox-item:after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 25%;
    background-color: #fff;
    content: "";
  }
  &-side:before {
    z-index: 1;
    background-color: #001529;
    content: "";
  }
  &-mix:after {
    background-color: #001529;
  }
  &-icon {
    position: absolute;
    right: 6px;
    bottom: 4px;
    color: #1890ff;
    font-weight: 700;
    font-size: 14px;
    pointer-events: none;
  }
}
</style>
